import React, { useState, FC, useEffect } from 'react';
import { useForm, useField } from '@formily/react';
import { TextWidget } from '@inbiz/react';
import { useRequest } from '@umijs/hooks';
import { Button, Select, Form, message, Modal as ModalAntd } from 'antd';
import { getManyFields, getModelData } from '../service';
import './style.less';
const { Option } = Select;

const prefixCls = 'inbiz-Transfer-designer-subtableConfigModal';

export type IValue = {
  modelKey: string;
  RefId: string;
  id: string;
};

interface ILocale {
  title: string;
  model: string;
  requiredmessage: string;
}
interface IProps {
  value: IValue;
  onChange: (v: IValue) => void;
}

const SubtableConfigModal: FC<IProps> = ({ value, onChange }) => {
  const globalForm = useForm();
  const [form] = Form.useForm();
  const takeMessage = useField().takeMessage() as ILocale;
  const [visible, setVisible] = useState(false);
  const {
    data: modelData = [],
    run: getModelDataAsync,
    loading: modelLoading,
  } = useRequest(getModelData, { manual: true });

  const {
    data: fieldsData = [],
    run: getManyFieldsAsync,
    loading: fieldsLoading,
  } = useRequest(
    (modelKeys: string) => getManyFields({ appId: globalForm.appInfo.appId, modelKeys }),
    {
      manual: true,
      formatResult: (res) => res?.[0]?.Fields || [],
    },
  );

  const showModal = () => {
    if (!globalForm.fields?.['form.senior.soure.x-component-props.sourceModel']?.value) {
      message.warn('请先选择查询数据源');
      return;
    }
    setVisible(true);
  };

  const onCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  const onOk = async () => {
    const formValue = await form.validateFields();
    onChange(formValue);
    setVisible(false);
  };

  useEffect(() => {
    if (visible) {
      getModelDataAsync({ appId: globalForm.appInfo.appId });
      if (value?.modelKey) {
        getManyFieldsAsync(value.modelKey);
      }
      form.setFieldsValue(value);
    }
  }, [visible, globalForm, value]);

  return (
    <>
      <Button type="primary" onClick={showModal}>
        {takeMessage.title || '存储配置'}
      </Button>
      <ModalAntd
        className={prefixCls}
        title={takeMessage.title || '配置'}
        visible={visible}
        width={450}
        bodyStyle={{ padding: '32px 64px' }}
        onCancel={onCancel}
        onOk={onOk}
        okText={<TextWidget>global.sure</TextWidget>}
        cancelText={<TextWidget>.global.cancel</TextWidget>}
        destroyOnClose
      >
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
          <Form.Item
            label={takeMessage.model || '模型'}
            name="modelKey"
            rules={[{ required: true, message: takeMessage.requiredmessage || '该字段必填' }]}
          >
            <Select allowClear loading={modelLoading} onChange={getManyFieldsAsync}>
              {modelData.map((item) => (
                <Option key={item.ModelKey} value={item.ModelKey}>
                  {item.ModelName}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="Refld"
            name="RefId"
            rules={[{ required: true, message: takeMessage.requiredmessage || '该字段必填' }]}
          >
            <Select allowClear loading={fieldsLoading}>
              {fieldsData.map((item) => (
                <Option key={item.Key} value={item.Key}>
                  {item.Name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="ID"
            name="id"
            rules={[{ required: true, message: takeMessage.requiredmessage || '该字段必填' }]}
          >
            <Select allowClear loading={fieldsLoading}>
              {fieldsData.map((item) => (
                <Option key={item.Key} value={item.Key}>
                  {item.Name}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </ModalAntd>
    </>
  );
};

export default SubtableConfigModal;
